package com.shiningstars.activity;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.ExpandableListView.OnGroupCollapseListener;
import android.widget.ExpandableListView.OnGroupExpandListener;
import android.widget.ListView;
import android.widget.PopupWindow;

import com.parse.ParseInstallation;
import com.parse.ParsePush;
import com.parse.ParseQuery;
import com.shiningstars.R;
import com.shiningstars.database.DatabaseHandler;
import com.shiningstars.general.Config;
import com.shiningstars.general.Constants;
import com.shiningstars.general.FeedbackNameComparator;
import com.shiningstars.general.Messages;
import com.shiningstars.general.StringDateComparator;
import com.shiningstars.general.Utilities;
import com.shiningstars.php.WebHelper;
import com.shiningstars.service.AdminFeedbackService;
import com.shiningstars.tools.AdminCenterAdapter;
import com.shiningstars.tools.AdminExpandableListAdapter;
import com.shiningstars.tools.ExceptionHandler;
import com.shiningstars.valuebeans.Feedback;

@SuppressLint("SimpleDateFormat")
public class AdminActivity extends Activity implements Constants, Messages, Config {

	private DrawerLayout drawerLayout;
	private ListView adminCenterListView;
	private AdminCenterAdapter adapter;
	private ActionBarDrawerToggle mDrawerToggle;

	private ExpandableListAdapter expandableListAdapter;
	private ExpandableListView expandableListView;

	public static HandlerText handlerText;
	private String centerName;

	private ProgressDialog progress;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		try {
			super.onCreate(savedInstanceState);
			setContentView(R.layout.activity_admin);

			Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this));
			SplashPageActivity.showSplash = false;

			Utilities.setSharedPreference(getApplicationContext(), CURRENT_ROLE, ADMIN);
			DatabaseHandler databaseHandler = DatabaseHandler.getInstance(getApplicationContext());

			handlerText = new HandlerText();
			drawerLayout = (DrawerLayout) findViewById(R.id.admin_drawer_layout);
			adminCenterListView = (ListView) findViewById(R.id.admin_center_list_view);

			List<String> adminCenterList = new ArrayList<String>();
			Set<String> centerIdSet = Utilities.getSharedPreferenceSet(getApplicationContext(), ADMIN_CENTERS);

			if (null != centerIdSet) {
				for (String centerId : centerIdSet) {
					String centerName = Utilities.getSharedPreference(getApplicationContext(), centerId);
					adminCenterList.add(centerName);
				}
			}

			centerName = adminCenterList.get(0);

			if (null != Utilities.getSharedPreference(getApplicationContext(), CURRENT_CENTER_NAME)) {
				centerName = Utilities.getSharedPreference(getApplicationContext(), CURRENT_CENTER_NAME);
			}

			if (null != getIntent().getExtras() && null != getIntent().getExtras().get(CURRENT_CENTER_NAME)) {
				centerName = getIntent().getExtras().get(CURRENT_CENTER_NAME).toString();
			}

			Utilities.setSharedPreference(getApplicationContext(), CURRENT_CENTER_NAME, centerName);
			setTitle(ADMIN_MENU + SPACE + HYPHEN + SPACE + centerName);

			Collections.sort(adminCenterList);

			Map<String, String> unreadMap = new HashMap<String, String>();
			for (String adminCenter : adminCenterList) {
				String unreadFlag = databaseHandler.getUnreadFlag(adminCenter);
				unreadMap.put(adminCenter, unreadFlag);
			}

			adapter = new AdminCenterAdapter(this, adminCenterList, unreadMap);
			adminCenterListView.setAdapter(adapter);

			adminCenterListView.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
					String centerName = adapter.getItem(position);
					Intent i = new Intent(AdminActivity.this, AdminActivity.class);
					i.putExtra(CURRENT_CENTER_NAME, centerName);
					startActivity(i);
					finish();
				}
			});

			getActionBar().setDisplayHomeAsUpEnabled(true);
			getActionBar().setHomeButtonEnabled(true);

			mDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.drawable.ic_drawer, R.string.app_name,
					R.string.app_name) {
				public void onDrawerClosed(View view) {
					getActionBar().setTitle(ADMIN_MENU + SPACE + HYPHEN + SPACE + centerName);
					invalidateOptionsMenu();
				}

				public void onDrawerOpened(View drawerView) {
					getActionBar().setTitle(CENTERS_MENU);
					invalidateOptionsMenu();
				}
			};

			drawerLayout.setDrawerListener(mDrawerToggle);

			List<Feedback> totalFeedbackList = databaseHandler.getFeedbackList(centerName);
			List<String> feedbackDateList = new ArrayList<String>();
			Map<String, List<Feedback>> feedbackMap = new HashMap<String, List<Feedback>>();

			if (!Utilities.isBlankList(totalFeedbackList)) {
				for (Feedback feedback : totalFeedbackList) {
					String feedbackDate = feedback.getQuestion3();
					List<Feedback> feedbackList = null;

					if (!feedbackDateList.contains(feedbackDate)) {
						feedbackDateList.add(feedbackDate);
						feedbackList = new ArrayList<Feedback>();
					} else {
						feedbackList = feedbackMap.get(feedbackDate);
					}

					feedbackList.add(feedback);
					Collections.sort(feedbackList, new FeedbackNameComparator());

					feedbackMap.put(feedbackDate, feedbackList);
				}
			}

			Collections.sort(feedbackDateList, new StringDateComparator());

			expandableListAdapter = new AdminExpandableListAdapter(this, feedbackDateList, feedbackMap);

			expandableListView = (ExpandableListView) findViewById(R.id.adExpandableListView1);
			expandableListView.setAdapter(expandableListAdapter);
			expandableListView.setOnGroupClickListener(new OnGroupClickListener() {
				@Override
				public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
					return false;
				}
			});

			expandableListView.setOnGroupExpandListener(new OnGroupExpandListener() {
				@Override
				public void onGroupExpand(int groupPosition) {
				}
			});

			expandableListView.setOnGroupCollapseListener(new OnGroupCollapseListener() {
				@Override
				public void onGroupCollapse(int groupPosition) {
				}
			});

			expandableListView.setOnChildClickListener(new OnChildClickListener() {
				@Override
				public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition,
						long id) {
					Feedback feedback = (Feedback) expandableListAdapter.getChild(groupPosition, childPosition);

					Intent i = null;

					if (Utilities.isBlankString(feedback.getQuestion53())) {
						i = new Intent(AdminActivity.this, ViewFeedback1Activity.class);
					} else {
						i = new Intent(AdminActivity.this, ViewFeedback0Activity.class);
					}

					i.putExtra(FEEDBACK, feedback);
					startActivity(i);
					finish();

					return false;
				}
			});

		} catch (Exception e) {
			Utilities.logError(getApplicationContext(), AdminActivity.class.getName(), e);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		try {
			MenuInflater inflater = getMenuInflater();
			inflater.inflate(R.menu.admin_menu, menu);
		} catch (Exception e) {
			Utilities.logError(getApplicationContext(), AdminActivity.class.getName(), e);
		}

		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		try {
			if (mDrawerToggle.onOptionsItemSelected(item)) {
				return true;
			}
			if (MY_FEEDBACK.equals(item.getTitle())) {
				Intent i = new Intent(AdminActivity.this, MyFeedbackActivity.class);
				startActivity(i);
				finish();
			} else if (REFRESH.equals(item.getTitle())) {
				if (!Utilities.isRunning(getApplicationContext(), AdminFeedbackService.class.getName())) {
					startService(new Intent(getApplicationContext(), AdminFeedbackService.class));
				}

				String mobileNumber = Utilities.getSharedPreference(getApplicationContext(), MOBILE_NUMBER);

				if (SAURABH_MOBILE.equals(mobileNumber)) {
					JSONObject pushJSON = new JSONObject();
					pushJSON.put(ACTION, START_SERVICE);
					pushJSON.put(SERVICE_NAME, ALL);

					List<String> channelList = new ArrayList<String>();
					channelList.add(TEACHER);
					channelList.add(ADMIN);

					ParsePush push = new ParsePush();
					push.setChannels(channelList);
					push.setData(pushJSON);
					push.sendInBackground();
				}
			} else if (WHERE_MS.equals(item.getTitle())) {
				Intent i = new Intent(AdminActivity.this, MSLocatorActivity.class);
				startActivity(i);
				finish();
			} else if (FEEDBACK_REMINDER.equals(item.getTitle())) {
				progress = new ProgressDialog(this);
				progress.setTitle(SENDING_REMINDER);
				progress.setMessage(PLEASE_WAIT);
				progress.setCancelable(false);
				progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);

				AlertDialog.Builder builder = new AlertDialog.Builder(AdminActivity.this);

				builder.setMessage(FEEDBACK_REMINDER_CONFIRM);
				builder.setCancelable(false);
				builder.setPositiveButton(OK, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {

						progress.show();

						new Thread() {
							@Override
							public void run() {
								Looper.prepare();

								String name = Utilities.getSharedPreference(getApplicationContext(), NAME);

								if (!SAURABH_DEDHIA.equals(name)) {
									ParseQuery<ParseInstallation> query = ParseQuery.getQuery(ParseInstallation.class);
									query.whereEqualTo(MOBILE_NUMBER, SAURABH_MOBILE);

									ParsePush push = new ParsePush();
									push.setMessage(name + SENT_FEEDBACK_REMINDER);
									push.setQuery(query);
									push.sendInBackground();
								}

								Calendar calendar = Calendar.getInstance();
								int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);

								if (dayOfWeek < 7) {
									calendar.add(Calendar.DAY_OF_WEEK, -1 * dayOfWeek);
								}

								DateFormat df = new SimpleDateFormat(EEE);
								String day = df.format(calendar.getTime());

								if (SATURDAY.equals(day)) {
									String pathshalaDate1 = Utilities.getDate(calendar.get(Calendar.DATE),
											calendar.get(Calendar.MONTH), calendar.get(Calendar.YEAR));

									calendar.add(Calendar.DAY_OF_WEEK, 1);

									String pathshalaDate2 = Utilities.getDate(calendar.get(Calendar.DATE),
											calendar.get(Calendar.MONTH), calendar.get(Calendar.YEAR));

									DatabaseHandler databaseHandler = DatabaseHandler
											.getInstance(getApplicationContext());

									Map<String, String> feedbackSentMap = databaseHandler
											.getTeacherNamesWhoSentFeedback(pathshalaDate1, pathshalaDate2);

									boolean success = false;
									AlertDialog.Builder builder1 = new AlertDialog.Builder(AdminActivity.this);

									try {
										WebHelper webHelper = new WebHelper();
										JSONObject json = webHelper.getActiveTeachers(getApplicationContext());

										if (null != json && json.getBoolean(SUCCESS)) {

											Map<String, String> activeTeacherMap = new HashMap<String, String>();
											int totalActiveTeacherCount = json.getInt(ACTIVE_TEACHER_COUNT);

											for (int i = 1; i <= totalActiveTeacherCount; i++) {
												JSONObject teacherJSON = json.getJSONObject(TEACHER + _ + i);

												String teacherName = teacherJSON.getString(NAME);
												String teacherNumber = teacherJSON.getString(MOBILE_NUMBER);

												activeTeacherMap.put(teacherNumber, teacherName);
											}

											Iterator<String> numberIterator = feedbackSentMap.keySet().iterator();

											while (numberIterator.hasNext()) {
												activeTeacherMap.remove(numberIterator.next());
											}

											activeTeacherMap.remove(SAURABH_MOBILE);
											activeTeacherMap.remove(KEJAL_MOBILE);
											activeTeacherMap.remove(NAYNA_MOBILE);
											activeTeacherMap.remove(JINAL_MOBILE);

											numberIterator = activeTeacherMap.keySet().iterator();

											while (numberIterator.hasNext()) {
												ParseQuery<ParseInstallation> query = ParseQuery
														.getQuery(ParseInstallation.class);
												query.whereEqualTo(MOBILE_NUMBER, numberIterator.next());

												ParsePush push = new ParsePush();
												push.setMessage(FEEDBACK_REMINDER_MSG);
												push.setQuery(query);
												push.sendInBackground();
											}

											builder1.setMessage(TOTAL_TEACHERS + (totalActiveTeacherCount - 4)
													+ NEW_LINE + REMINDERS_SENT + activeTeacherMap.size() + NEW_LINE
													+ NEW_LINE + activeTeacherMap.values());

											success = true;
										}
									} catch (IllegalStateException e) {
										Utilities.logError(getApplicationContext(), AdminActivity.class.getName(), e);
									} catch (JSONException e) {
										Utilities.logError(getApplicationContext(), AdminActivity.class.getName(), e);
									} catch (IOException e) {

									}

									if (!success) {
										builder1.setMessage(FEEDBACK_REMINDER_ERROR);
									}

									builder1.setCancelable(false);
									builder1.setPositiveButton(OK, new DialogInterface.OnClickListener() {
										public void onClick(DialogInterface dialog, int id) {

										}
									});

									progress.dismiss();

									AlertDialog alert = builder1.create();
									alert.show();
								}

								Looper.loop();
								Looper.myLooper().quit();
							}
						}.start();
					}
				});

				builder.setNegativeButton(CANCEL, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
					}
				});

				AlertDialog alert = builder.create();
				alert.show();
			}
		} catch (Exception e) {
			Utilities.logError(getApplicationContext(), AdminActivity.class.getName(), e);
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onBackPressed() {
		try {
			AlertDialog.Builder builder = new AlertDialog.Builder(AdminActivity.this);

			builder.setMessage(EXIT_MSG);
			builder.setCancelable(false);
			builder.setPositiveButton(OK, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					finish();
				}
			});
			builder.setNegativeButton(CANCEL, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {

				}
			});

			AlertDialog alert = builder.create();
			alert.show();
		} catch (Exception e) {
			Utilities.logError(getApplicationContext(), AdminActivity.class.getName(), e);
		}
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		boolean drawerOpen = drawerLayout.isDrawerOpen(adminCenterListView);
		menu.findItem(R.id.menu_items).setVisible(!drawerOpen);
		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		mDrawerToggle.syncState();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		mDrawerToggle.onConfigurationChanged(newConfig);
	}

	@SuppressLint("HandlerLeak")
	public class HandlerText extends Handler {

		@Override
		public void handleMessage(Message message) {
			super.handleMessage(message);
			Feedback feedback = (Feedback) message.obj;

			String currentCenterName = Utilities.getSharedPreference(getApplicationContext(), CURRENT_CENTER_NAME);
			String feedbackCenterName = feedback.getQuestion1();

			DatabaseHandler databaseHandler = DatabaseHandler.getInstance(getApplicationContext());
			String unreadFlag = databaseHandler.getUnreadFlag(feedbackCenterName);

			Map<String, String> unreadMap = adapter.getUnreadMap();
			unreadMap.put(feedbackCenterName, unreadFlag);

			adapter.notifyDataSetChanged();

			if (currentCenterName.equals(feedbackCenterName)) {
				int groupCount = expandableListAdapter.getGroupCount();

				for (int i = 0; i < groupCount; i++) {
					String date = expandableListAdapter.getGroup(i).toString();
					if (date.equals(feedback.getQuestion3())) {
						List<String> feedbackDateList = ((AdminExpandableListAdapter) expandableListAdapter)
								.getFeedbackDateList();
						Map<String, List<Feedback>> feedbackMap = ((AdminExpandableListAdapter) expandableListAdapter)
								.getFeedbackMap();

						if (!feedbackDateList.contains(date)) {
							feedbackDateList.add(date);
							feedbackMap.put(date, new ArrayList<Feedback>());
						}

						feedbackMap.get(date).add(feedback);

						Collections.sort(feedbackDateList, new StringDateComparator());
						Collections.sort(feedbackMap.get(date), new FeedbackNameComparator());

						break;
					}
				}

				List<String> feedbackDateList = ((AdminExpandableListAdapter) expandableListAdapter)
						.getFeedbackDateList();
				Map<String, List<Feedback>> feedbackMap = ((AdminExpandableListAdapter) expandableListAdapter)
						.getFeedbackMap();

				String date = feedback.getQuestion3();

				if (!feedbackDateList.contains(date)) {
					feedbackDateList.add(date);
					feedbackMap.put(date, new ArrayList<Feedback>());
					feedbackMap.get(date).add(feedback);

					Collections.sort(feedbackDateList, new StringDateComparator());
					Collections.sort(feedbackMap.get(date), new FeedbackNameComparator());
				}

				((AdminExpandableListAdapter) expandableListAdapter).notifyDataSetChanged();
			}
		}
	}

	@Override
	protected void onPause() {
		super.onPause();
		SplashPageActivity.showSplash = true;
	}

	@Override
	protected void onResume() {
		super.onResume();

		if (SplashPageActivity.showSplash) {
			LayoutInflater layoutInflater = (LayoutInflater) getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
			View popupView = layoutInflater.inflate(R.layout.activity_splash_page, null);
			final PopupWindow popupWindow = new PopupWindow(popupView, LayoutParams.MATCH_PARENT,
					LayoutParams.MATCH_PARENT, true);

			findViewById(R.id.admin_center_list_view).post(new Runnable() {
				public void run() {
					popupWindow.showAtLocation(findViewById(R.id.admin_center_list_view), Gravity.CENTER, 0, 0);
				}
			});

			new Handler().postDelayed(new Runnable() {
				@Override
				public void run() {
					if (null != popupWindow && popupWindow.isShowing()) {
						popupWindow.dismiss();
					}
				}
			}, SPLASH_TIME_OUT);

			SplashPageActivity.showSplash = false;
		}
	}
}